package com.zhiyume.service;

import com.zhiyume.dao.api.TCmsRecommendMapper;
import com.zhiyume.dao.entity.TCmsRecommend;
import com.zhiyume.dao.entity.TCmsRecommendCriteria;
import com.zhiyume.service.util.StringUtil;
import com.zhiyume.util.TypeConstants;
import com.zhiyume.vo.CommonReqVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wang on 18/1/18.
 */
@Service
@Transactional
public class CmsRecommendService {

    @Autowired
    private TCmsRecommendMapper tCmsRecommendMapper;


    public List<TCmsRecommend> getCmsRecommendList(CommonReqVO page){
        List<TCmsRecommend> cms = new ArrayList<>();

        TCmsRecommendCriteria t = new TCmsRecommendCriteria();
        TCmsRecommendCriteria.Criteria c= t.createCriteria();

        if(page.getDataId()>-1){
            //本框架所用分页算法
            c.andIdGreaterThan(page.getDataId());
            t.setLimitStart(0);
            t.setLimitEnd(page.getPageSize());
        }else{
            t.setLimitStart(page.getPage()*page.getPageSize());
            t.setLimitEnd(page.getPageSize());
        }

        //排序
        t.setOrderByClause("id desc,`r_id` desc");

        createCritera(page, c);

        cms = tCmsRecommendMapper.selectByExample(t);
        return cms;
    }

    private void createCritera(CommonReqVO page, TCmsRecommendCriteria.Criteria c) {
        //兼容焦点图配置 add by wangxq 2018/03/06
        if(page.getType()!=null){
            c.andTypeEqualTo(page.getType().toString());
        }
        if(StringUtil.isNotBlank(page.getTitle())){
            c.andFromTitleLike("%"+page.getTitle()+"%");
        }
        if(StringUtil.isNotBlank(page.getStartTime())){
            c.andCreateTimeGreaterThanOrEqualTo(page.getStartTime());
        }
        if(StringUtil.isNotBlank(page.getEndTime())){
            c.andCreateTimeLessThanOrEqualTo(page.getEndTime());
        }
        if(StringUtil.isNotBlank(page.getStatus())){
            c.andStatusEqualTo(page.getStatus());
        }

        //默认有效啊 03/16
        if(TypeConstants.COMMON_VALID.equals(page.getStatus())){
            c.andStatusEqualTo(TypeConstants.COMMON_VALID);
        }else{
            c.andStatusEqualTo(TypeConstants.COMMON_INVALID);
        }
    }

    public int getCmsRecommendCount(CommonReqVO page){

        int count = 0;
        TCmsRecommendCriteria t = new TCmsRecommendCriteria();
        TCmsRecommendCriteria.Criteria c= t.createCriteria();

        //本框架所用分页算法
        if(page.getDataId()>-1){
            //本框架所用分页算法
            c.andIdGreaterThan(page.getDataId());
        }

        createCritera(page,c);

        count = tCmsRecommendMapper.countByExample(t);
        return count;
    }
}
